﻿#include "pch.h"

namespace fs = std::filesystem;


// 测试固件
class OrgFileTest : public ::testing::Test
{
protected:
    void SetUp() override
    {        
        // 创建测试文件
        std::ofstream("test.org") << "dummy content";
        validHandle = createOrgFile("test_org");
        ASSERT_GT(validHandle, 0);
    }

    void TearDown() override
    {
        // 清理测试文件
        fs::remove("test.org");
        fs::remove("saved.org");
    }

    int64_t validHandle = -1;
    const int32_t validChannel = 0;
    const int32_t invalidChannel = -1;
};

// 测试用例1：基本生命周期
TEST_F(OrgFileTest, FileLifecycle)
{
    // 创建新句柄
    int64_t newHandle = createOrgFile("new_org");
    ASSERT_GT(newHandle, 0);

    // 验证基础数据
    TOrgHead head;
    EXPECT_TRUE(getOrgHead(newHandle, &head));
    EXPECT_STREQ(head.Name, "new_org");

    // 保存文件
    EXPECT_TRUE(saveOrgFile(newHandle, "saved.org"));

    // 关闭文件
    EXPECT_TRUE(closeOrgFile(newHandle));

    // 验证关闭后操作失效
    EXPECT_FALSE(getOrgHead(newHandle, &head));
    EXPECT_EQ(getLastErrorCode(), ERR_CODE_ORG_HANDLE_NOT_EXIST);
}

// 啥也不干2
TEST_F(OrgFileTest, NoneTest2)
{
    std::cout << "啥也不干2" << std::endl;
}

// 测试用例2：无效句柄操作
TEST_F(OrgFileTest, InvalidHandleOperations)
{
    const int64_t invalidHandle = 999;

    // 测试所有函数对无效句柄的处理
    TOrgHead head;
    EXPECT_FALSE(getOrgHead(invalidHandle, &head));
    EXPECT_EQ(getLastErrorCode(), ERR_CODE_ORG_HANDLE_NOT_EXIST);

    EXPECT_FALSE(saveOrgFile(invalidHandle, "test"));
    EXPECT_FALSE(closeOrgFile(invalidHandle));

    // 数据操作测试
    TRawItem dummy = {0, 0, 0};
    int32_t count = 0;
    EXPECT_FALSE(getOrgRawData(invalidHandle, validChannel, &dummy, 1, &count));
}

// 测试用例3：通道边界检查
TEST_F(OrgFileTest, ChannelBoundaryCheck)
{
    TOrgHead head;
    ASSERT_TRUE(getOrgHead(validHandle, &head));

    // 获取最大通道数
    const int32_t maxChannel = 4;
    const int32_t invalidChannel = 4;

    // 测试有效通道
    TRawItem dummy = {0, 0, 0};
    int32_t count = 0;
    EXPECT_TRUE(getOrgRawData(validHandle, validChannel, &dummy, 1, &count));

    // 测试无效通道
    EXPECT_FALSE(getOrgRawData(validHandle, invalidChannel, &dummy, 1, &count));
    EXPECT_EQ(getLastErrorCode(), ERR_CODE_IPARAM_VALUE_INVALID);
}

// 测试用例4：空指针参数检查
TEST_F(OrgFileTest, NullPointerCheck)
{
    // get函数空指针
    EXPECT_FALSE(getOrgHead(validHandle, nullptr));
    EXPECT_EQ(getLastErrorCode(), ERR_CODE_PPARA_IS_NULL);

    // set函数空指针
    EXPECT_FALSE(setOrgHead(validHandle, nullptr));
    EXPECT_EQ(getLastErrorCode(), ERR_CODE_PPARA_IS_NULL);

    // 数据操作空指针
    int32_t count = 0;
    TRawItem dummy = {0, 0, 0};
    EXPECT_FALSE(getOrgRawData(validHandle, validChannel, nullptr, 1, &count));
    EXPECT_FALSE(getOrgRawData(validHandle, validChannel, &dummy, 1, nullptr));
}

// 测试用例5：原始数据操作
TEST_F(OrgFileTest, RawDataOperations)
{
    // 准备测试数据
    const std::vector<TRawItem> testData{{0, 0, 1}, {0, 0, 2}, {0, 0, 3}, {0, 0, 4}, {0, 0, 5}};

    // 设置数据
    EXPECT_TRUE(setOrgRawData(validHandle, validChannel, testData.data(), (int32_t)testData.size()));

    // 获取数据
    std::vector<TRawItem> buffer(testData.size());
    int32_t count = 0;
    EXPECT_TRUE(getOrgRawData(validHandle, validChannel, buffer.data(), (int32_t)buffer.size(), &count));

    // 验证数据
    EXPECT_EQ(count, testData.size());
    EXPECT_EQ(buffer, testData);

    // 测试缓冲区不足
    buffer.resize(testData.size() - 1);
    EXPECT_FALSE(getOrgRawData(validHandle, validChannel, buffer.data(), (int32_t)buffer.size(), &count));
    EXPECT_EQ(getLastErrorCode(), ERR_CODE_BUFFER_INSUFFICIENT);
    EXPECT_EQ(count, testData.size()); // 返回实际数据量
}

// 测试用例6：分析结果操作
TEST_F(OrgFileTest, AnalysisResultOperations)
{
    // 准备测试数据
    std::vector<TAnalResult> results(2);
    results[0] = {1.1, 2.2, 3.3, 4};
    results[1] = {5.5, 6.6, 7.7, 8};

    // 设置数据
    EXPECT_TRUE(setOrgAnalResult(validHandle, validChannel, results.data(), (int32_t)results.size()));

    // 获取数据
    std::vector<TAnalResult> buffer(results.size());
    int32_t count = 0;
    EXPECT_TRUE(getOrgAnalResult(validHandle, validChannel, buffer.data(), (int32_t)buffer.size(), &count));

    // 验证数据
    EXPECT_EQ(count, results.size());
    for (size_t i = 0; i < results.size(); ++i)
    {
        EXPECT_DOUBLE_EQ(buffer[i].AreaPer, results[i].AreaPer);
    }
}

// 测试用例7：文件操作异常
TEST_F(OrgFileTest, FileOperationExceptions)
{
    // 打开不存在的文件
    int64_t handle = openOrgFile("nonexistent.org");
    EXPECT_EQ(handle, -1);
    EXPECT_EQ(getLastErrorCode(), ERR_CODE_FILE_NOT_EXISTS);

    // 测试读取损坏文件
    std::ofstream("corrupt.org") << "invalid data";
    handle = openOrgFile("corrupt.org");
    EXPECT_EQ(handle, -1);
    EXPECT_EQ(getLastErrorCode(), ERR_CODE_FILE_PARSE_FAILED);

    // 测试保存到只读目录
    fs::create_directory("readonly_dir");
    fs::permissions("readonly_dir", fs::perms::owner_write | fs::perms::group_write | fs::perms::others_write, fs::perm_options::remove);
#ifdef _WIN32
    EXPECT_TRUE(saveOrgFile(validHandle, "readonly_dir/test.org"));
    EXPECT_EQ(getLastErrorCode(), 0);
#else
    EXPECT_FALSE(saveOrgFile(validHandle, "readonly_dir/test.org"));
    EXPECT_EQ(getLastErrorCode(), ERR_CODE_FILE_OPEN_FAILED);
#endif
    fs::remove_all("readonly_dir");
}

// 测试用例8：数据边界值测试
TEST_F(OrgFileTest, DataBoundaryTests)
{
    // 测试最大数据量
    std::vector<TRawItem> maxData(MAX_DOTS, {0, 0, 1});
    EXPECT_TRUE(setOrgRawData(validHandle, validChannel, maxData.data(), MAX_DOTS));

    // 测试超过最大值
    std::vector<TRawItem> overflowData(MAX_DOTS + 1);
    EXPECT_FALSE(setOrgRawData(validHandle, validChannel, overflowData.data(), MAX_DOTS + 1));
    EXPECT_EQ(getLastErrorCode(), ERR_CODE_IPARAM_VALUE_INVALID);

    // 测试空数据
    EXPECT_FALSE(setOrgRawData(validHandle, validChannel, nullptr, 0));
    EXPECT_EQ(getLastErrorCode(), ERR_CODE_PPARA_IS_NULL);
}

// 测试用例9：仪器条件操作
TEST_F(OrgFileTest, InstrumentConditionOperations)
{
    // 获取原始条件
    TInstCond original;
    ASSERT_FALSE(getOrgInstCond(validHandle, 0, &original));

    // 修改条件
    TInstCond modified = original;
    modified.OvenCond.MaxTemp = 250.0f;

    // 设置新条件
    EXPECT_TRUE(setOrgInstCond(validHandle, 0, &modified));

    // 验证修改
    TInstCond current;
    EXPECT_TRUE(getOrgInstCond(validHandle, 0, &current));
    EXPECT_FLOAT_EQ(current.OvenCond.MaxTemp, 250.0f);
}

// 测试用例10：综合结果测试
TEST_F(OrgFileTest, SyntheticResultOperations)
{
    // 准备测试数据
    TSynResult result{};
    result.Height = 100.0;
    result.ConcEx = 1.5;

    // 设置数据
    EXPECT_TRUE(setOrgSynResult(validHandle, validChannel, &result, 1));

    // 获取数据
    TSynResult buffer[1];
    int32_t count = 0;
    EXPECT_TRUE(getOrgSynResult(validHandle, validChannel, buffer, 1, &count));

    // 验证数据
    EXPECT_EQ(count, 1);
    EXPECT_DOUBLE_EQ(buffer[0].Height, 100.0);
}

// 测试用例11：重新积分功能
TEST_F(OrgFileTest, ReanalysisFunction)
{
    // 准备基础数据
    TOrgHead head{};
    std::string test_str = "analysis_test";
    char *pSource = (char *)test_str.c_str();
    std::copy(pSource, pSource + MIN(strlen(pSource) + 1, sizeof(head.Name)), head.Name);
    head.Name[sizeof(head.Name) - 1] = 0;
    ASSERT_TRUE(setOrgHead(validHandle, &head));

    // 执行重新积分
    EXPECT_FALSE(analysis(validHandle, -1));

    // 验证分析结果（假设分析会生成结果）
    TAnalResult results[10];
    int32_t count = 0;
    EXPECT_TRUE(getOrgAnalResult(validHandle, validChannel,
                                 results, 10, &count));
    EXPECT_GE(count, 0);
}
 
// 测试用例12：内存泄漏检查
TEST_F(OrgFileTest, MemoryLeakCheck)
{
    const int32_t initialHandles = getOrgMapSize();

    // 创建临时句柄
    int64_t tempHandle = createOrgFile("temp");
    ASSERT_GT(tempHandle, 0);

    // 显式关闭
    EXPECT_TRUE(closeOrgFile(tempHandle));

    // 验证句柄释放
    EXPECT_EQ(getOrgMapSize(), initialHandles);
}
#ifdef TEST_ORG
int32_t main(int32_t argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
#endif